package cn.psh.org.service.impl;

import cn.psh.basic.service.impl.BaseServiceImpl;
import cn.psh.org.domain.Department;
import cn.psh.org.mapper.DepartmentMapper;
import cn.psh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService  {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public List<Department> queryTree() {
        // 查询所有部门数据
        List<Department> allDepts = departmentMapper.queryAll();
        // 定义一个集合 用于装 组装好的数据
        List<Department> result = new ArrayList<>();
        // 将当前的集合 转成 map
        Map<Long, Department> deptMap = allDepts.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        // 组装数据
        for (Department dept : allDepts) {
            if (null != dept.getParentId()){
                // 当前的数据是儿子 一个儿子 只能有一个爹
                Department parent = deptMap.get(dept.getParentId());
                parent.getChildren().add(dept);
            }else {
                // 当前数据就是爹
                result.add(dept);
            }
        }
        return result;
    }
}
